import { type Ref, ref, onMounted, reactive } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";
import { message } from "@/utils/message";
import { getKeyList } from "@pureadmin/utils";
import { type PlusColumn } from "plus-pro-components";
import data from "@iconify-icons/ri/fullscreen-fill";
import { getOrderStatusList2 } from "@/api/dashboard";
import { createPaymentRecord } from "@/api/payment";
const ruleFormRef = ref();
const newFormInline = ref({
  totalAmount: 0,
  remark: "",
  orderIds: [],
  paidAt: "",
  paymentMethod: "",
  paymentSn: "",
  payerAccount: ""
});

const paymentmethodList = ref([
  {
    paymentmethod: "支付宝",
    name: "支付宝"
  },
  {
    paymentmethod: "微信",
    name: "微信"
  },
  {
    paymentmethod: "民生银行",
    name: "民生银行"
  },
  {
    paymentmethod: "中国银行",
    name: "中国银行"
  }
]);

const handleSubmit = async () => {
  const res = await createPaymentRecord(newFormInline.value);
  if (res.status.code === 200) {
    console.log("新增回款成功");
    message("新增回款成功", { type: "success" });
    ruleFormRef.value.resetFields();
  } else {
    message(res.status.msg, { type: "error" });
  }
};

// 订单搜索配置
export function useSearchTable(tableRef: Ref) {
  // 选中的数量
  const selectedNum = ref(0);
  // 规则表单实例
  const ruleFormRef = ref();
  // 新增表单实例
  // const newFormInline = ref();

  // 搜索状态
  const searchState = ref({
    orderno: "",
    purchasingunit: "",
    contactsname: "",
    minprice: 0,
    maxprice: 0,
    paymentdate: [], // 初始化为空数组，以匹配日期范围选择器的期望格式
    page: 1,
    size: 10
  });

  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });

  // 搜索表单配置
  const searchColumns: PlusColumn[] = [
    {
      label: "订单号",
      prop: "orderno",
      valueType: "textarea",
      colProps: {
        span: 8
      },
      fieldProps: {
        style: { width: "160px" }
      }
    },
    {
      label: "采购人",
      prop: "contactsname",
      valueType: "input",
      colProps: {
        span: 8
      }
    },
    {
      label: "采购单位",
      prop: "purchasingunit",
      valueType: "input",
      colProps: {
        span: 8
      }
    },
    {
      label: "最小金额",
      prop: "minprice",
      valueType: "input-number",
      colProps: {
        span: 8
      },
      fieldProps: {
        placeholder: "最低金额"
      }
    },
    {
      label: "最大金额",
      prop: "maxprice",
      valueType: "input-number",
      colProps: {
        span: 8
      },
      fieldProps: {
        placeholder: "最高金额"
      }
    },
    {
      label: "时间",
      prop: "paymentdate",
      valueType: "date-picker",
      fieldProps: {
        type: "daterange",
        valueFormat: "X",
        style: { width: "230px" }
      },
      colProps: {
        span: 11
      }
    }
  ];

  // 表格配置
  const tableColumns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "订单号",
      prop: "orderno",
      width: 180
    },
    {
      label: "订单时间",
      prop: "orderdate",
      width: 110
    },
    {
      label: "采购单位",
      prop: "purchasingunit"
    },
    {
      label: "采购人",
      prop: "contactsname",
      width: 100
    },
    {
      label: "订单金额",
      prop: "price",
      width: 120
    }
  ];
  // 表格数据
  const searchList = ref([]);

  /** 表格取消多选 */
  function onSelectionCancel() {
    // 获取当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();

    // 获取当前选中行的订单号
    const selectedOrderIds = getKeyList(curSelected, "orderno");

    // 从已选中的订单ID列表中移除当前选中的订单ID
    newFormInline.value.orderIds = newFormInline.value.orderIds.filter(
      orderno => !selectedOrderIds.includes(orderno)
    );

    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 表格多选事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 表格获取选中行数据 */
  function getSelectedRows() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();

    // 获取当前选中的订单号
    let res = getKeyList(curSelected, "orderno");

    // 在原有数据基础上增加新选中的订单号
    const combinedOrderIds = [...newFormInline.value.orderIds, ...res];

    // 去重处理
    newFormInline.value.orderIds = [...new Set(combinedOrderIds)];
  }

  function matchOrderIds(str: string) {
    // 使用正则表达式匹配空格(\s)、逗号(,)，其中\s已包含换行符(\n)等空白字符
    // +表示匹配一个或多个连续的分隔符，避免分割出空字符串
    const parts = str.split(/[\s,]+/);
    // 过滤掉可能存在的空字符串（如字符串首尾的分隔符导致）
    return parts.filter(item => item.length > 0);
  }

  /** 提交表单 */
  function handleSearch(values: any) {
    // 确保paymentdate是数组格式
    if (values.paymentdate && !Array.isArray(values.paymentdate)) {
      // 如果paymentdate不是数组，将其转换为空数组
      values.paymentdate = [];
    }

    // 同步搜索条件到状态，便于翻页时保留筛选
    searchState.value = {
      ...searchState.value,
      ...values
    };

    getStatusList(values);
  }

  const getStatusList = async values => {
    // 检查paymentdate是否为数组且长度大于0
    let orderIds = matchOrderIds(values.orderno);
    console.log("orderIds", orderIds);
    if (!Array.isArray(values.paymentdate) || values.paymentdate.length === 0) {
      // 如果没有选择日期，不传递时间参数，让后端返回所有时间的数据
      const res = await getOrderStatusList2({
        orderids: orderIds,
        purchasingunit: values.purchasingunit,
        contactsname: values.contactsname,
        minprice: values.minprice,
        maxprice: values.maxprice,
        page: values.page,
        size: values.size
      });
      searchList.value = res.data.orderlist || [];
      pagination.total = res.data.total || 0;
      return;
    }

    // 确保paymentdate数组有两个有效的时间戳
    const startTime = values.paymentdate[0]
      ? parseInt(values.paymentdate[0])
      : undefined;
    const endTime = values.paymentdate[1]
      ? parseInt(values.paymentdate[1])
      : undefined;

    const res = await getOrderStatusList2({
      orderids: orderIds,
      purchasingunit: values.purchasingunit,
      contactsname: values.contactsname,
      minprice: values.minprice,
      maxprice: values.maxprice,
      starttime: startTime,
      endtime: endTime,
      page: values.page,
      size: values.size
    });
    searchList.value = res.data.orderlist || [];
    pagination.total = res.data.total || 0;
  };

  function handlePageChange(val) {
    pagination.currentPage = val;
    searchState.value.page = val;
    getStatusList(searchState.value);
  }

  function handleSizeChange(val) {
    pagination.pageSize = val;
    searchState.value.size = val;
    getStatusList(searchState.value);
  }

  return {
    selectedNum,
    searchColumns,
    tableColumns,
    searchList,
    searchState,
    pagination,
    onSelectionCancel,
    handleSelectionChange,
    getSelectedRows,
    handleSearch,
    handlePageChange,
    handleSizeChange
  };
}

export { ruleFormRef, newFormInline, paymentmethodList, handleSubmit };
